import { BinaryToTextEncoding, createHash } from 'crypto';
import { ReadStream } from 'fs';

export default async function createFileHash(
  dataSource: ReadStream | Buffer | string,
  encodeType: BinaryToTextEncoding = 'hex',
): Promise<string> {
  const hash = createHash('sha256');

  return new Promise((resolve, reject) => {
    // 如果是流
    if (dataSource instanceof ReadStream) {
      const readStream = dataSource;
      readStream.on('data', function (d) {
        hash.update(d);
      });

      readStream.on('end', function () {
        const hashStr = hash.digest(encodeType);
        resolve(hashStr);
      });

      readStream.on('error', function (err) {
        reject(err);
      });
    }

    // 如果是字符串或者buffer
    if (dataSource instanceof Buffer || typeof dataSource === 'string') {
      hash.update(dataSource);
      const hashStr = hash.digest(encodeType);
      resolve(hashStr);
    }
  });
}
